<?php


namespace app\index\service;

use app\index\model\FormTemplate AS template;
use app\index\model\FormAnswer AS answer;
use think\Exception;

class FormService
{
    protected $user;
    protected $merchant_id;
    public function __construct(){
        global $user;
        $this->user = \app\index\model\User::where('id',$user['id'])->find();
        $this->merchant_id = $this->user['merchant_id'];
    }

    public function findAll(int $page, int $size){
        $form = template::where('status',1)
            ->where('mall_id',$this->user['mall_id'])
            ->order('create_time DESC')
            ->paginate(['page' => $page,'list_rows' => $size]);
        return [HTTP_SUCCESS,$form];
    }

    public function read(int $id){
        $form = template::find($id);
        return [HTTP_SUCCESS,$form];
    }

    public function answer(string $answer,int $template_id){
        $template = template::find($template_id);
        if ($template->tries_limit > 0){
            if(answer::count() >=  $template->tries_limit)
                throw new Exception('您已经到达上限',HTTP_INVALID);
        }
        $answer = answer::create([
            'user_id' => $this->user['id'],
            'template_id' => $template_id,
            'answer' => $answer,
            'merchant_id' => $this->user['merchant_id'],
            'create_time' => now(),
            'update_Time' => now()
        ]);
        return [HTTP_SUCCESS,$answer];
    }

    public function answerList(int $page,int $size){
        $list = answer::order('create_time DESC')
            ->paginate(['page' => $page,'list_rows' => $size]);
        return [HTTP_SUCCESS,$list];
    }

    public function answerRead(int $id){
        $answer = answer::find($id);
        return [HTTP_SUCCESS,$answer];
    }
}